package main.java.  factory.config_factory.bean;



import main.java.factory.factory_method.CoffeeFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class CofferFactory {
    //加载配置文件，获取文件中的全类名，并创建对象
    //1定义容器存储咖啡对象
    private static HashMap<String, Coffee> map = new HashMap();


    //2加载配置文件

    static {
        //创建properties 对象
        Properties p = new Properties();
        //调用load方法进行配置文件的加载
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            p.load(is);

            //从P对象中获取全类名并创建对象 p对象是个集合
            Set<Object> keys = p.keySet();
            for (Object key : keys) {
                String className = p.getProperty((String) key);
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                //将对象存储到容器
                map.put((String) key, coffee);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }


    public static Coffee createCoffee(String name) {
        return map.get(name);
    }
}
